package com.boot.security.server.controller.mffl.MfflConsultation;

import ch.qos.logback.core.encoder.EchoEncoder;
import com.boot.security.server.dao.UserDao;
import com.boot.security.server.dao.mffl.*;
import com.boot.security.server.dto.LoginUser;
import com.boot.security.server.model.SysUser;
import com.boot.security.server.model.mffl.*;
import com.boot.security.server.page.table.PageTableHandler;
import com.boot.security.server.page.table.PageTableRequest;
import com.boot.security.server.page.table.PageTableResponse;
import com.boot.security.server.page.table.PageTableHandler.ListHandler;
import com.boot.security.server.service.impl.mffl.Lawyerservicepeoplenumber.LawyerservicepeoplenumberService;
import com.boot.security.server.service.impl.mffl.MfflSystemMessages.MfflSystemMessagesImpl;
import com.boot.security.server.service.impl.mffl.WXPay.WXPayService;
import com.boot.security.server.utils.UserUtil;
import com.boot.security.server.utils.mffl.ProjectUtil;
import com.boot.security.server.utils.mffl.ReturnBean;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.boot.security.server.service.impl.mffl.MfflConsultation.MfflConsultationService;
import com.boot.security.server.service.impl.mffl.Mfflpublic.publicService;

import javax.servlet.http.HttpServletRequest;

import com.boot.security.server.page.table.PageTableHandler.CountHandler;
import springfox.documentation.annotations.ApiIgnore;
import com.boot.security.server.service.impl.mffl.MfflService.MfflServiceImpl;

import java.util.*;

@Api(tags = "免费咨询/付费咨询")
@RestController
@RequestMapping("/client/mfflConsultations")
public class Clinet_MfflConsultationController {
    @Autowired
    private MfflUserDao mfflUserDao;

    @Autowired
    private MfflConsultationDao mfflConsultationDao;

    @Autowired
    private MfflConsultationReplyDao mfflConsultationReplyDao;

    @Autowired
    private MfflConsultationlikeDao mfflConsultationlikeDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate<String, Map<String, String>> redisTemplate;

    @Autowired
    private MfflOrderDao mfflOrderDao;

    @Autowired
    private MfflTypeDao mfflTypeDao;

    //公共功能
    @Autowired
    private publicService publicService;

    //微信支付
    @Autowired
    WXPayService wxPayService;

    //微信支付
    @Autowired
    private WXPayService wxpayservice;

    //支入支出表
    @Autowired
    private MfflProfitDao mfflProfitDao;

    @Value("${Pay.NotifyIP}")
    public String NotifyIP;

    @Autowired
    MfflConsultationService MfflConsultationService;

    //服务人数
    @Autowired
    LawyerservicepeoplenumberService LawyerservicepeoplenumberService;

    //推送
    @Autowired
    MfflSystemMessagesImpl MfflSystemMessagesImpl;

    //用户表
    @Autowired
    MfflUserDao mffluserdao;

    //服务
    @Autowired
    private MfflServiceImpl MfflServiceImpl;

    //配置微信支付随机数
    @Value("${Pay.attach}")
    private String attach;

    //消息推送修改状态已读
    @Autowired
    MfflSystemMessagesDao mfflSystemMessagesDao;


    @Transactional(rollbackFor = Exception.class)
    @PostMapping
    @ApiOperation(value = "提交免费/付费咨询")
    public ReturnBean save(@ApiParam(value = "咨询类型id(0免费,1付费)", name = "freeorpaid", required = true) @RequestParam(required = true) Integer freeorpaid,
                           @ApiParam(value = "类型id（婚姻，劳务，商务）", name = "type", required = true) @RequestParam(required = true) String type,
                           @ApiParam(value = "内容", name = "content", required = true) @RequestParam(required = true) String content,
                           @ApiParam(value = "图片地址(按照分号分割)", name = "imageurl") @RequestParam(required = false) String imageurl,
                           @ApiParam(value = "对方态度", name = "defendantattitude") @RequestParam(required = false) String defendantattitude,
                           @ApiParam(value = "对方态度图片（图片id，多张图片分号分割）", name = "defendanturl") @RequestParam(required = false) String defendanturl,
                           @ApiParam(value = "我的诉求", name = "myappeal") @RequestParam(required = false) String myappeal,
                           @ApiParam(value = "金额，（double类型）", name = "money") @RequestParam(required = false) String money,
                           @ApiParam(value = "悬赏时间（天数）", name = "deadline") @RequestParam(required = false) Integer deadline,
                           @ApiParam(value = "我的态度图片", name = "myappealurl") @RequestParam(required = false) String myappealurl) throws Exception {
        ReturnBean returnBean;
        if (StringUtils.isEmpty(freeorpaid)) {
            return new ReturnBean("201", "freeorpaid不能为空");
        }
        if (StringUtils.isEmpty(type)) {
            return new ReturnBean("201", "type不能为空");
        }
        if (StringUtils.isEmpty(content)) {
            return new ReturnBean("201", "content不能为空");
        }
        if (mfflTypeDao.getByTypeId(Integer.parseInt(type), 1) == null) {
            return new ReturnBean("201", "所选类型不存在");
        }
        if (deadline != null && deadline > 100) {
            return new ReturnBean("201", "设置天数过长");
        }
        if (deadline != null && deadline < 0) {
            return new ReturnBean("201", "设置天数过短");
        }
        //检查输入金额
        if (freeorpaid == 1) {
            MfflService byServiceId = MfflServiceImpl.getByServiceId(2L);
            try {
                if (Double.parseDouble(money) < byServiceId.getMinimumMoney()) {
                    return new ReturnBean("201", "最小金额不允许小于" + (int) byServiceId.getMinimumMoney());
                }
            } catch (Exception e) {
                if (Double.parseDouble(money) < 20) {
                    return new ReturnBean("201", "最小金额不允许小于" + (int) byServiceId.getMinimumMoney());
                }
            }
        }

        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        Date date = new Date();
        MfflConsultation mfflConsultation = new MfflConsultation();
        mfflConsultation.setUserid(sysUser.getId().intValue());
        mfflConsultation.setServiceId(freeorpaid == 1 ? 2 : 1);
        mfflConsultation.setTitle("");
        mfflConsultation.setImageUrl(imageurl == null ? "" : imageurl);
        mfflConsultation.setDefendantAttitude(defendantattitude == null ? "" : defendantattitude);
        mfflConsultation.setMyAttitude("");
        mfflConsultation.setDeadline(new Date());//截止日期
        mfflConsultation.setRewarddays(deadline == null ? 3 : deadline);//悬赏天数
        mfflConsultation.setMoney(freeorpaid == 1 ? Double.parseDouble(money) : 0);
        mfflConsultation.setLawyerId(0);
        mfflConsultation.setTradingState(0);
        mfflConsultation.setFreeOrPaid(freeorpaid == 1 ? 1 : 0);
        mfflConsultation.setFreeOrPaidName(freeorpaid == 1 ? "专业咨询" : "免费咨询");
        mfflConsultation.setPayId(0);
        mfflConsultation.setPayNumber("");
        String PayMerchantNumber = ProjectUtil.payMerchantNumber();
        mfflConsultation.setPayMerchantNumber(PayMerchantNumber);
        mfflConsultation.setBestAnswerId(0);
        mfflConsultation.setHot(0);
        mfflConsultation.setType(Integer.valueOf(type));
        mfflConsultation.setLikeNumber(0);
        mfflConsultation.setDeleteState(1);
        mfflConsultation.setCollectNumber(0);
        mfflConsultation.setDeleteTime(date);
        mfflConsultation.setContent(content);
        mfflConsultation.setMyAppeal(myappeal == null ? "" : myappeal);
        mfflConsultation.setDefendantUrl(defendanturl == null ? "" : defendanturl);
        mfflConsultation.setReplyNumber(0);
        mfflConsultation.setMyappealurl(myappealurl == null ? "" : myappealurl);
        //免费咨询就直接完成，付费咨询就是代付款状态
        mfflConsultation.setState(freeorpaid == 1 ? 0 : 1);//0待支付1正常2完结
        int save = mfflConsultationDao.save(mfflConsultation);
        //付费创建订单
        if (freeorpaid == 1) {
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setPayNumber("");
            mfflOrder.setPayMerchantNumber(PayMerchantNumber);
            mfflOrder.setServierId(2);
            mfflOrder.setServiceName("专业咨询");
            mfflOrder.setMoney(Double.parseDouble(money));
            mfflOrder.setUserid(sysUser.getId().intValue());
            mfflOrder.setCreateTime(new Date());
            mfflOrder.setUpdtaeTime(new Date());
            mfflOrder.setDeleteStae(1);
            mfflOrder.setDeleteTime(new Date());
            mfflOrder.setTypeid(Integer.valueOf(type));
            mfflOrder.setProductId(mfflConsultationDao.getBypaymerchantnumber(PayMerchantNumber).getId().intValue());
            mfflOrder.setState(0);
            int saveOrderDa = mfflOrderDao.save(mfflOrder);

            //咨询关联订单
            MfflConsultation mfll = new MfflConsultation();
            mfll.setId(mfflConsultation.getId());
            mfll.setPayId(mfflOrder.getId().intValue());
            mfflConsultationDao.update(mfll);

            //订单创建成功
            if (saveOrderDa == 1) {
                returnBean = new ReturnBean();
                returnBean.setDatas(PayMerchantNumber);

            } else {
                returnBean = new ReturnBean();
                returnBean.setReturnBean("105");
            }
            return returnBean;
        }
        if (save == 1) {
            returnBean = new ReturnBean();
        } else {
            returnBean = new ReturnBean();
            returnBean.setReturnBean("105");
        }
        return returnBean;
    }


    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询免费/付费咨询详情")
    public ReturnBean<MfflConsultation> get(@PathVariable Long id) {
        //获取当前系统用户
        SysUser sysUser = UserUtil.getLoginUser();

        if (id == null) {
            return new ReturnBean("201", "id不能为空");
        }

        ReturnBean returnBean = new ReturnBean();
        try {
            //咨询
            MfflConsultation byId = mfflConsultationDao.getById(id);

            if (byId == null) {
                return new ReturnBean("201", "当前查看的咨询不存在");
            }
            //多图片处理图片处理
            if (!StringUtils.isEmpty(byId.getImageUrl())) {
                List<Map<String, Object>> maps = new ArrayList<>();
                String[] split = byId.getImageUrl().split(";");
                for (String time : split) {
                    Map<String, Object> map = ProjectUtil.imageUrlAll(time);
                    maps.add(map);
                }
                byId.setImageUrlList(maps);
            }

            //多图片处理图片处理
            if (!StringUtils.isEmpty(byId.getDefendantUrl())) {
                List<Map<String, Object>> maps = new ArrayList<>();
                String[] split = byId.getDefendantUrl().split(";");
                for (String time : split) {
                    Map<String, Object> map = ProjectUtil.imageUrlAll(time);
                    maps.add(map);
                }
                byId.setDefendantUrlList(maps);
            }

            if (byId != null) {
                //插入用户信息
                byId.setUserinfo(mfflUserDao.getUserInfoSimple(byId.getUserid()));
                //插入咨询类型
                Integer type = byId.getType();
                MfflType byId1 = mfflTypeDao.getById(type.longValue());
                byId.setTypename(byId1.getName());

                //回复
                List<MfflConsultationReply> consultationIdList = mfflConsultationReplyDao.getConsultationIdList(byId.getId());

                //分类
                for (int i = 0; i < consultationIdList.size(); i++) {
                    //找出追评添加到回复里
                    Integer param1 = consultationIdList.get(i).getConsultationId().intValue();//标题id
                    Long param2 = consultationIdList.get(i).getId().longValue();//主回复id

                    mfflUserSimple userInfoSimple = mfflUserDao.getUserInfoSimple(consultationIdList.get(i).getUserid());
                    consultationIdList.get(i).setUserinfo(userInfoSimple);//插入用户信息
                    //是否参与过回复或追评，没有为null有则为对应id
                    if (userInfoSimple.getId() == sysUser.getId()) {
                        byId.setStatus(consultationIdList.get(i).getId().intValue());
                    }

                    //遍历查询出无层级回复 插入用户信息
                    List<MfflConsultationReply> consultationIdAppendList = mfflConsultationReplyDao.getConsultationIdAppendList(param1, param2);

                    //追评数据插入用户信息
                    for (int j = 0; j < consultationIdAppendList.size(); j++) {
                        //插入用户信息
                        consultationIdAppendList.get(j).setUserinfo(mfflUserDao.getUserInfoSimple(consultationIdAppendList.get(j).getUserid()));

                    }
                    consultationIdList.get(i).setConsultationReplyList(consultationIdAppendList);
                }
                byId.setReplyList(consultationIdList);
                returnBean.setDatas(byId);
            } else {
                returnBean.setReturnBean("106");
            }
            MfflConsultationService.setHot(id);

        } catch (Exception e) {
            //失败返回操作失败
            returnBean.setReturnBean("105");
            e.printStackTrace();
        }
        return returnBean;
    }


    @ApiOperation(value = "专业/免费咨询回复")
    @PostMapping(value = "replyconsultation")
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean replyConsultation(@ApiParam(name = "consultationid", value = "问题id", required = true) @RequestParam String consultationid,
                                        @ApiParam(name = "appendid", value = "被追评id（0为正常回复，其他为被追评答案的id）", required = true) @RequestParam String appendid,
                                        @ApiParam(name = "reply", value = "回复内容", required = true) @RequestParam String reply) throws Exception{
        ReturnBean returnBean;
        if (StringUtils.isEmpty(consultationid)) {
            return new ReturnBean("201", "consultationid不能为空");
        }
        if (StringUtils.isEmpty(reply)) {
            return new ReturnBean("201", "reply不能为空");
        }
        if (StringUtils.isEmpty(appendid)) {
            return new ReturnBean("201", "appendid不能为空");
        }


        //获取当前系统用户
        SysUser sysUser = UserUtil.getLoginUser();
        //获取系统附属表
        MfflUser byUserId = mfflUserDao.getByUserId(sysUser.getId());

        //查看律师是否通过认证
        if (byUserId.getIdentity() == 1) {
            if (byUserId.getLawyerInspect() != 1) {
                returnBean = new ReturnBean();
                returnBean.setReturnBean("137");
                return returnBean;
            }
        }


        if (Integer.valueOf(appendid) != 0) {
            MfflConsultationReply appendReplyData = mfflConsultationReplyDao.getById(Long.parseLong(appendid));
            if (appendReplyData == null) {
                return new ReturnBean("201", "要追评的数据不存在");
            } else {
                //追评数加1
                MfflConsultationReply mctr = new MfflConsultationReply();
                mctr.setId(appendReplyData.getId());
                mctr.setReplynumber(appendReplyData.getReplynumber() == null ? 1 : appendReplyData.getReplynumber() + 1);
                mctr.setUpdateTime(null);
                mfflConsultationReplyDao.update(mctr);

                //律师服务人数增加
                if (byUserId.getIdentity() == 1) {
                    //增加服务人数
                    LawyerservicepeoplenumberService.increaseLawyerservicepeoplenumber(sysUser.getId().intValue());
                }
            }
        }

        //咨询数据
        MfflConsultation byId = mfflConsultationDao.getById(Long.parseLong(consultationid));

        if (byId == null) {
            return new ReturnBean("201", "当前id对应的数据不存在");
        }

        if (byId.getState() == 0 && byId.getFreeOrPaid() == 1) {
            return new ReturnBean("201", "当前付费咨询未付费，暂不允许回复");
        }

        if (byId != null) {
            try {
                //回复
                MfflConsultationReply mfflConsultationReply = new MfflConsultationReply();
                mfflConsultationReply.setUserid(sysUser.getId().intValue());
                mfflConsultationReply.setLawyer(0);
                mfflConsultationReply.setUserOrLawyer(byUserId.getIdentity());
                mfflConsultationReply.setConsultationId(Integer.parseInt(consultationid));
                mfflConsultationReply.setServiceType(0);
                mfflConsultationReply.setReply(reply);
                mfflConsultationReply.setImageUrl("");
                mfflConsultationReply.setPayId(0);
                mfflConsultationReply.setPayMerchantNumber("");
                mfflConsultationReply.setPayNumber("");
                mfflConsultationReply.setAppend(Integer.parseInt(appendid));
                mfflConsultationReply.setDeleteState(1);
                mfflConsultationReply.setDeleteTime(new Date());
                mfflConsultationReply.setRewardnumber(0);
                mfflConsultationReply.setReplynumber(0);
                int save = mfflConsultationReplyDao.save(mfflConsultationReply);

                //回复人不为本人时推送
                if (sysUser.getId() != byId.getUserid().longValue()) {
                    MfflSystemMessagesImpl.sendMessage(publicService.MessageModel(byId.getServiceId() == 2 ? "[专业咨询]咨询有新回复" : "[免费咨询]咨询有新回复", byId.getPayMerchantNumber()), byId.getServiceId().toString(), byId.getId().intValue(), byId.getUserid());
                }


                //修改问题回复数量
                if (save == 1) {
                    byId.setReplyNumber(byId.getReplyNumber() + 1);
                    byId.setUpdateTime(null);
                    mfflConsultationDao.update(byId);
                }
                returnBean = new ReturnBean();
            } catch (Exception e) {
                returnBean = new ReturnBean();
                returnBean.setReturnBean("105");
                e.printStackTrace();
                throw new Exception("操作异常"+e.getMessage());
            }
        } else {
            returnBean = new ReturnBean();
            returnBean.setReturnBean("106");
        }
        return returnBean;
    }


    @GetMapping(value = "setbestanswer")
    @ApiOperation(value = "设置最佳答案")
    public ReturnBean setBestAnswer(
            @ApiParam(name = "id", value = "问题id", required = true) @RequestParam String id,
            @ApiParam(name = "bestanswerid", value = "最佳答案id", required = true) @RequestParam String bestanswerid) {
        ReturnBean returnBean = null;

        if (StringUtils.isEmpty(id)) {
            return new ReturnBean("201", "id不能为空");
        }
        if (StringUtils.isEmpty(bestanswerid)) {
            return new ReturnBean("201", "bestanswerid不能为空");
        }

        LoginUser loginUser = UserUtil.getLoginUser();
        HashMap<String, Integer> params = new HashMap<>();

        //最佳答案的回复知否存在
        params.put("userid", loginUser.getId().intValue());
        params.put("consultation", Integer.parseInt(id));
        params.put("consultationreply", Integer.parseInt(bestanswerid));

        //回复
        MfflConsultationReply bestAnswer = mfflConsultationReplyDao.getBestAnswer(params);
        //问题
        MfflConsultation byId = mfflConsultationDao.getById(bestAnswer.getConsultationId().longValue());


        //查看问题是否已有最佳答案
        if (byId.getBestAnswerId() == 0) {
            if (bestAnswer != null) {
                //判断咨询是否是当前用户的
                if (loginUser.getId().intValue() != byId.getUserid()) {
                    return new ReturnBean("201", "该咨询不是当前用户的，无权进行操作");
                }

                //设为最佳答案
                MfflConsultation mfflConsultation = new MfflConsultation();
                mfflConsultation.setId(bestAnswer.getConsultationId().longValue());
                mfflConsultation.setBestAnswerId(bestAnswer.getId().intValue());
                mfflConsultation.setTradingState(1);
                //mfflConsultation.setState(2);
                mfflConsultation.setUpdateTime(null);
                mfflConsultationDao.update(mfflConsultation);

                //如果为付费咨询则修改状态
                if (byId.getFreeOrPaid() == 1) {
                    //修改订单状态
                    MfflOrder order = mfflOrderDao.getBypaymerchantnumber(byId.getPayMerchantNumber());

                    //新增支入支出表---律师
                    MfflProfit mlp = new MfflProfit();
                    mlp.setOrderId(order.getId().intValue());
                    mlp.setUserId(bestAnswer.getUserid());
                    mlp.setServciceName("专业咨询");
                    mlp.setState(1);           //0未结算，1已经算
                    mlp.setMoney(order.getMoney());
                    mlp.setSettlement(1);
                    mlp.setCreateTime(new Date());
                    mlp.setUpdateTime(new Date());
                    mlp.setDeduction(0.0);
                    mfflProfitDao.update(mlp);

                    //修改用户金额
                    MfflUser byId1 = mfflUserDao.getByUserId(bestAnswer.getUserid().longValue());
                    MfflUser mfflUser = new MfflUser();
                    mfflUser.setId(byId1.getId());
                    mfflUser.setMoney(ProjectUtil.addition(byId1.getMoney(), byId.getMoney()));
                    mfflUserDao.update(mfflUser);
                }
                //推送
                MfflSystemMessagesImpl.sendMessage(publicService.MessageModel(byId.getServiceId() == 1 ? "[专业咨询]" : "[免费咨询]" + "回复被设为最佳答案", byId.getPayMerchantNumber()), byId.getServiceId().toString(), byId.getId().intValue(), bestAnswer.getUserid());
                returnBean = new ReturnBean();
            } else {
                returnBean.setReturnBean("106");
            }
        } else {
            returnBean = new ReturnBean();
            returnBean.setReturnBean("108");
        }
        return returnBean;
    }


    @PutMapping
    @ApiOperation(value = "修改")
    public ReturnBean update(@ApiParam(name = "id", value = "id", required = true) @RequestParam Long id,
                             @ApiParam(name = "type", value = "类型", required = false) @RequestParam(required = false) Integer type,
                             @ApiParam(name = "myAppeal", value = "我的诉求", required = false) @RequestParam(required = false) String myAppeal,
                             @ApiParam(name = "imageUrl", value = "图片", required = false) @RequestParam(required = false) String imageUrl,
                             @ApiParam(name = "defendantUrl", value = "对方态度图片", required = false) @RequestParam(required = false) String defendantUrl,
                             @ApiParam(name = "defendantAttitude", value = "对方态度", required = false) @RequestParam(required = false) String defendantAttitude,
                             @ApiParam(name = "content", value = "要修改的问题的内容", required = false) @RequestParam(required = false) String content) {
        ReturnBean returnbean;
        if (id == null) {
            return new ReturnBean("201", "id不能为空");
        }

        if (type != null) {
            if (mfflTypeDao.getByTypeId(type, 1) == null) {
                return new ReturnBean("201", "所选类型不存在");
            }
        }

        //如果有回复不允许修改
        if (mfflConsultationReplyDao.getEarliest(id) != null) {
            return new ReturnBean("201", "当前咨询已有回复，不允许修改");
        }

        //查看该id的问题是否属于该用户
        LoginUser loginUser = UserUtil.getLoginUser();
        HashMap<String, Long> map = new HashMap<>();
        map.put("userid", loginUser.getId().longValue());
        map.put("id", id);
        MfflConsultation userConsultationid = mfflConsultationDao.getUserConsultationid(map);
        if (userConsultationid != null) {
            if (userConsultationid.getBestAnswerId() == 0) {
                //可以修改
                MfflConsultation mfftaion = new MfflConsultation();
                mfftaion.setId(userConsultationid.getId());
                mfftaion.setType(type == null ? userConsultationid.getType() : type);
                //问题内容
                mfftaion.setContent(content == null ? userConsultationid.getContent() : content);
                //图片
                mfftaion.setImageUrl(imageUrl == null ? userConsultationid.getImageUrl() : imageUrl);
                //对方态度
                mfftaion.setDefendantAttitude(defendantAttitude == null ? userConsultationid.getDefendantAttitude() : defendantAttitude);
                //对方态度图片
                mfftaion.setDefendantUrl(defendantUrl == null ? userConsultationid.getDefendantUrl() : defendantUrl);
                //我的诉求
                mfftaion.setMyAppeal(myAppeal == null ? userConsultationid.getMyAppeal() : myAppeal);
                int update = mfflConsultationDao.update(mfftaion);

                if (update == 1) {
                    returnbean = new ReturnBean();
                    returnbean.setReturnBean("200");
                } else {
                    returnbean = new ReturnBean();
                    returnbean.setReturnBean("105");
                }
            } else {
                //已经有最佳答案不修改
                returnbean = new ReturnBean();
                returnbean.setReturnBean("108");
            }
        } else {
            returnbean = new ReturnBean();
            returnbean.setReturnBean("106");
        }
        return returnbean;
    }

    @PostMapping(value = "rewardPay")
    @ApiOperation(value = "支付接口")
    public ReturnBean rewardPay(@ApiParam(name = "paymerchantnumber", value = "订单号", required = true) @RequestParam String paymerchantnumber) {
        if (StringUtils.isEmpty(paymerchantnumber)) {
            return new ReturnBean("201", "paymerchantnumber不能为空");
        }
        ReturnBean returnBean = MfflConsultationService.ServicePay(paymerchantnumber, "/client/mfflConsultations/wechatpaycallback");
        if ("123".equals(returnBean.getErrCode())) {
            //订单号重复支付修改订单号，修改数据订单号
            //修改合同订单号  修改order订单号
            //订单操作
            MfflOrder Order = mfflOrderDao.getBypaymerchantnumber(paymerchantnumber);

            //咨询
            MfflConsultation bypaymerchantnumber = mfflConsultationDao.getBypaymerchantnumber(paymerchantnumber);

            //重新生成订单号
            String newpayMerchantNumber = ProjectUtil.payMerchantNumber();

            //创建一个实体，防止在修改过程中其他信息改变的风险
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setId(Order.getId());
            mfflOrder.setPayMerchantNumber(newpayMerchantNumber);
            mfflOrder.setUpdtaeTime(null);
            mfflOrderDao.update(mfflOrder);

            //创建一个实体，防止在修改过程中其他信息改变的风险
            MfflConsultation ml = new MfflConsultation();
            ml.setId(bypaymerchantnumber.getId());
            ml.setPayMerchantNumber(newpayMerchantNumber);
            ml.setUpdateTime(null);
            mfflConsultationDao.update(ml);

            ReturnBean returnbean = new ReturnBean();
            returnbean.setReturnBean("142");
            returnbean.setDatas(new HashMap<String, String>() {{
                put("newpayMerchantNumber", newpayMerchantNumber);
            }});
            return returnbean;
        }
        return returnBean;
    }


    /**
     * 查询订单状态
     * <p>
     * 如果查询微信订单为已支付并且本地order未改变，则修改状态
     *
     * @param payMerchantNumber
     * @return
     */
    @PostMapping(value = "orderquery")
    @ApiOperation(value = "查询订单状态")
    public ReturnBean orderquery(@ApiParam(name = "payMerchantNumber", value = "商户订单号", required = true) @RequestParam String payMerchantNumber) {
        ReturnBean returnbean = new ReturnBean();
        try {
            Map<String, String> orderquery = wxpayservice.orderquery(payMerchantNumber);
            MfflOrder Order = mfflOrderDao.getByPaymerchantNumberlocking(payMerchantNumber);
            if (!(orderquery.containsKey("trade_state") && orderquery.get("trade_state").equals("SUCCESS")) || Order.getState() == 0) {
                MfflOrder mfflOrder = new MfflOrder();
                mfflOrder.setId(Order.getId());
                mfflOrder.setState(5);//支付中
                mfflOrder.setUpdtaeTime(new Date());
                mfflOrderDao.update(mfflOrder);
                returnbean.setReturnBean("139");
                return returnbean;
            }

            //订单操作
            String payNumber = orderquery.get("transaction_id");
            //专业咨询状态
            MfflConsultation lawyerLetter = mfflConsultationDao.getById(Order.getProductId().longValue());
            //如果状态未改变则改变状态
            if (lawyerLetter.getState() == 0 || (Order.getState() == 0 || Order.getState() == 5)) {
                //修改咨询状态
                MfflConsultation bypaymerchantnumber = mfflConsultationDao.getBypaymerchantnumber(payMerchantNumber);
                //修改订单状态
                MfflOrder order = mfflOrderDao.getBypaymerchantnumber(payMerchantNumber);
                //如果已支付返回true
                if (order.getState() == 1 && bypaymerchantnumber.getState() == 1) {
                    return returnbean;
                }
                MfflConsultation mfflConsultation = new MfflConsultation();
                mfflConsultation.setId(bypaymerchantnumber.getId());
                mfflConsultation.setPayNumber(payNumber);               //支付单号
                //当前时间+悬赏时间=支付后悬赏时间
                mfflConsultation.setDeadline(new Date(new Date().getTime() + Long.valueOf((((bypaymerchantnumber.getRewarddays() * 24) * 60) * 60) * 1000)));
                mfflConsultation.setState(1);
                mfflConsultation.setUpdateTime(null);
                mfflConsultationDao.update(mfflConsultation);


                MfflOrder mfflOrder = new MfflOrder();
                mfflOrder.setId(order.getId());
                mfflOrder.setPayNumber(payNumber);
                mfflOrder.setState(1);      //0待支付，1支付，2退款 , 4申请退款
                mfflOrderDao.update(mfflOrder);

                //收入支出表
                List<MfflProfit> byOrderId = mfflProfitDao.getOrderId(mfflOrder.getId().intValue());
                Date date = new Date();
                if (byOrderId.size() == 0) {
                    MfflProfit mp = new MfflProfit();
                    mp.setOrderId(order.getId().intValue());
                    mp.setUserId(bypaymerchantnumber.getUserid()); //用户id
                    mp.setServciceName(bypaymerchantnumber.getFreeOrPaidName());
                    mp.setState(0);               //0支出，1收益,
                    mp.setMoney(order.getMoney());  //支出不扣点
                    mp.setSettlement(1);          //0未结算，1已经算
                    mp.setCreateTime(date);
                    mp.setSettlementTime(date);
                    mp.setDeduction(0.0);
                    mp.setUpdateTime(date);
                    mfflProfitDao.save(mp);
                }
                return returnbean;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnbean;
    }


    /**
     * 支付回调
     *
     * @param request
     * @return
     * @throws Exception
     */
    @ApiIgnore
    @RequestMapping(value = "wechatpaycallback")
    @ApiOperation(value = "微信回调接口（忽视）")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public String WechatPayCallback(HttpServletRequest request) throws Exception {
        //处理微信回调数据
        Map<String, String> returnmap = wxPayService.WechatPayCallback(request);
        boolean state = true;
        try {
            //修改订单信息
            String paymerchantnumber = returnmap.get("out_trade_no");//商户订单号
            String payNumber = returnmap.get("transaction_id");      //交易单号
            String nonceStr = returnmap.get("attach");               //随机数

            //验证随机数
            if (!attach.equals(nonceStr)) {
                System.out.println("验证随机数不通过");
                state = false;
            }

            //修改咨询状态
            MfflConsultation bypaymerchantnumber = mfflConsultationDao.getBypaymerchantnumber(paymerchantnumber);
            //修改订单状态
            MfflOrder order = mfflOrderDao.getBypaymerchantnumber(paymerchantnumber);
            //如果已支付返回true
            if (order.getState() == 1 && bypaymerchantnumber.getState() == 1) {
                return wxPayService.WechatPayCallbackReturnData(true);
            }
            MfflConsultation mfflConsultation = new MfflConsultation();
            mfflConsultation.setId(bypaymerchantnumber.getId());

            if (StringUtils.isEmpty(bypaymerchantnumber.getPayId()) || bypaymerchantnumber.getPayId() == 0) {
                mfflConsultation.setPayId(order.getId().intValue());
            }

            mfflConsultation.setPayNumber(payNumber);               //支付单号
            mfflConsultation.setState(1);
            //当前时间+悬赏时间=支付后悬赏时间
            mfflConsultation.setDeadline(new Date(new Date().getTime() + Long.valueOf((((bypaymerchantnumber.getRewarddays() * 24) * 60) * 60) * 1000)));
            mfflConsultation.setUpdateTime(null);
            mfflConsultationDao.update(mfflConsultation);


            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setId(order.getId());
            mfflOrder.setPayNumber(payNumber);
            mfflOrder.setState(1);      //0待支付，1支付，2退款 , 4申请退款
            mfflOrderDao.update(mfflOrder);

            //收入支出表
            List<MfflProfit> byOrderId = mfflProfitDao.getOrderId(mfflOrder.getId().intValue());
            Date date = new Date();
            if (byOrderId.size() == 0) {
                MfflProfit mp = new MfflProfit();
                mp.setOrderId(order.getId().intValue());
                mp.setUserId(bypaymerchantnumber.getUserid()); //用户id
                mp.setServciceName(bypaymerchantnumber.getFreeOrPaidName());
                mp.setState(0);               //0支出，1收益,
                mp.setMoney(order.getMoney());  //支出不扣点
                mp.setSettlement(1);          //0未结算，1已经算
                mp.setCreateTime(date);
                mp.setSettlementTime(date);
                mp.setDeduction(0.0);
                mp.setUpdateTime(date);
                mfflProfitDao.save(mp);
            }

        } catch (Exception e) {
            e.printStackTrace();
            state = false;
        }
        //微信回调数据
        return wxPayService.WechatPayCallbackReturnData(state);
    }


    @GetMapping
    @ApiOperation(value = "用户自己发布咨询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(required = true, name = "offset", value = "开始条数", dataType = "int"),
            @ApiImplicitParam(required = true, name = "limit", value = "每页条数", dataType = "int"),
            @ApiImplicitParam(required = true, name = "freeOrPaid", value = "0免费咨询，1专业咨询", paramType = "int")})
    public ReturnBean<MfflConsultation> list(PageTableRequest request) {
        if (request.getOffset() == null) {
            return new ReturnBean("201", "offset不能为空");
        }
        if (request.getLimit() == null) {
            return new ReturnBean("201", "limit不能为空");
        }
        if (request.getParams().get("freeOrPaid") == null) {
            return new ReturnBean("201", "freeOrPaid不能为空");
        }
        LoginUser loginUser = UserUtil.getLoginUser();
        request.getParams().put("deleteState", 1);
        request.getParams().put("userid", loginUser.getId());
        PageTableResponse handle = new PageTableHandler(new CountHandler() {
            @Override
            public int count(PageTableRequest request) {
                return mfflConsultationDao.count(request.getParams());
            }
        }, new ListHandler() {
            @Override
            public List<MfflConsultation> list(PageTableRequest request) {
                return mfflConsultationDao.list(request.getParams(), request.getOffset(), request.getLimit());
            }
        }).handle(request);

        List<MfflConsultation> MfflConsultationdata = (List<MfflConsultation>) handle.getData();

        for (int i = 0; i < MfflConsultationdata.size(); i++) {
            Integer type = MfflConsultationdata.get(i).getType();
            MfflType byId = mfflTypeDao.getById(type.longValue());
            MfflConsultationdata.get(i).setTypename(byId.getName());
        }
        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(handle);
        return returnBean;
    }


    @GetMapping(value = "participatelist")
    @ApiOperation(value = "查看自己参与过的专业咨询/免费咨询")
    @ApiImplicitParams({
            @ApiImplicitParam(required = true, name = "offset", value = "开始条数", dataType = "int"),
            @ApiImplicitParam(required = true, name = "limit", value = "每页条数", dataType = "int"),
            @ApiImplicitParam(required = true, name = "freeOrPaid", value = "0免费咨询，1专业咨询", paramType = "int")})
    public ReturnBean<MfflConsultation> participatelist(PageTableRequest request) {
        if (request.getOffset() == null) {
            return new ReturnBean("201", "offset不能为空");
        }
        if (request.getLimit() == null) {
            return new ReturnBean("201", "limit不能为空");
        }
        if (!request.getParams().containsKey("freeOrPaid")) {
            return new ReturnBean("201", "freeOrPaid不能为空");
        }
        LoginUser loginUser = UserUtil.getLoginUser();
        request.getParams().put("deleteState", 1);
        request.getParams().put("free_or_paid", request.getParams().get("freeOrPaid"));
        request.getParams().put("userid", loginUser.getId());

        return MfflConsultationService.participatelist(request);
    }


    @DeleteMapping("/{id}")
    @ApiOperation(value = "取消发布")
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean delete(@PathVariable Long id) throws Exception {
        if (id == null) {
            return new ReturnBean("201", "id不能为空");
        }
        ReturnBean returnbean = new ReturnBean();
        try {
            //获取当前用户
            SysUser sysUser = UserUtil.getLoginUser();

            MfflConsultation byId = mfflConsultationDao.getById(id);
            if (byId.getTradingState() == 3) {
                return new ReturnBean("201", "当前状态为已退款，无需操作");
            }

            //当前操作对象不为空
            if (byId != null) {
                if (sysUser.getId().intValue() != byId.getUserid()) {
                    return new ReturnBean("201", "咨询不属于当前用户，无法操作");
                }

                //有回复
                if (byId.getReplyNumber() != 0) {
                    return new ReturnBean("201", "当前咨询有回复，不能执行取消发布操作");
                }

                //有回复
                if (byId.getFreeOrPaid() == 1) {
                    if (byId.getState() != 1) {
                        return new ReturnBean("201", "当前咨询未支付，不能执行取消发布操作");
                    }
                }

                //完成状态
                if (byId.getTradingState() == 1) {
                    return new ReturnBean("201", "当前为完成状态，不能执行取消发布操作");
                }

            /*
            0免费--直接取消
            1付费--修改咨询状态，订单状态，支出收入表，退款
             */
                MfflConsultation mfflsn = new MfflConsultation();
                //免费咨询
                if (byId.getFreeOrPaid() == 0) {
                    mfflsn.setId(byId.getId());
                    mfflsn.setTradingState(3);//服务状态(0未完成,1完成,3取消发布)
                    //mfflsn.setDeleteState(0);
                    mfflConsultationDao.update(mfflsn);
                } else {
                    //订单状态
                    MfflOrder order = mfflOrderDao.getBypaymerchantnumber(byId.getPayMerchantNumber());
                    returnbean = MfflConsultationService.cancel(order.getPayMerchantNumber());
                    if ("200".equals(returnbean.getErrCode())) {
                        //付费咨询
                        mfflsn.setId(byId.getId());
                        mfflsn.setTradingState(3);//服务状态(0未完成,1完成,3取消发布)
                        //mfflsn.setDeleteState(0);
                        mfflConsultationDao.update(mfflsn);

                        //获取支入支出表---用户
                        MfflProfit userProfit = mfflProfitDao.getByOrderId(order.getId().intValue(), sysUser.getId().intValue());
                        //修改支付支出表--用户
                        MfflProfit mp = new MfflProfit();
                        mp.setId(userProfit.getId());
                        mp.setSettlement(2);//0未结算，1已经算 ， 2退款，3 申请退款
                        mp.setUpdateTime(new Date());
                        mfflProfitDao.update(mp);
                    }
                }
            } else {
                returnbean = new ReturnBean();
                returnbean.setReturnBean("106");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("异常错误");
        }
        return returnbean;
    }


    @PostMapping(value = "Reward")
    @ApiOperation(value = "打赏下单，返回商户单号")
    public ReturnBean Reward(@ApiParam(name = "id", value = "问题id", required = true) @RequestParam Long id,
                             @ApiParam(name = "replyId", value = "回复id（被打赏的回复的那条id）", required = true) @RequestParam Integer replyId,
                             @ApiParam(name = "money", value = "打赏金额(最小单位/分)", required = true) @RequestParam Integer money) {
        ReturnBean returnBean = new ReturnBean();

        //获取当前用户
        LoginUser loginUser = UserUtil.getLoginUser();

        if (id == null) {
            return new ReturnBean("201", "Id不能为空");
        }
        if (replyId == null) {
            return new ReturnBean("201", "replyId不能为空");
        }
        //咨询
        MfflConsultation mffct = mfflConsultationDao.getById(id);

        HashMap<String, Integer> params = new HashMap<>();
        params.put("userid", loginUser.getId().intValue());
        params.put("consultation", id.intValue());
        params.put("consultationreply", replyId);

        //回复表
        MfflConsultationReply replydata = mfflConsultationReplyDao.getById((long) replyId);
        if (mffct == null) {
            returnBean.setErrCode("201");
            returnBean.setMessage("当前问题不存在");
            return returnBean;
        }

        if (replydata == null && replydata.getConsultationId() == mffct.getId().intValue()) {
            returnBean.setErrCode("201");
            returnBean.setMessage("当前要打赏的评论不存在");
            return returnBean;
        }

        //被打赏的用户id
        Integer rewardUser = replydata.getUserid();

        //查看律师是否通过认证
        MfflUser byId = mffluserdao.getByUserId(rewardUser.longValue());
        if (byId.getIdentity() == 1) {
            if (byId.getLawyerInspect() != 1) {
                returnBean = new ReturnBean();
                returnBean.setReturnBean("137");
                return returnBean;
            }
        }

        try {
            //创建订单
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setPayNumber("");
            String payMerchantNumber = ProjectUtil.payMerchantNumber(); //获取商户订单号
            mfflOrder.setPayMerchantNumber(payMerchantNumber);  //获取商户订单号
            mfflOrder.setServierId(8);                 //服务id
            mfflOrder.setServiceName("打赏");                    //服务名称
            mfflOrder.setMoney(Double.parseDouble(money.toString()) / 100);//金额
            mfflOrder.setUserid(loginUser.getId().intValue());
            Date date = new Date();
            mfflOrder.setCreateTime(date);
            mfflOrder.setUpdtaeTime(date);
            mfflOrder.setDeleteTime(date);
            mfflOrder.setDeleteStae(1);                         //是否删除(0删除,1正常)
            mfflOrder.setTypeid(rewardUser);                             //类型id改为被打赏人id
            mfflOrder.setState(0);                              //0待支付，1支付，2退款
            mfflOrder.setProductId(replydata.getId().intValue());//订单关联
            mfflOrderDao.save(mfflOrder);
            returnBean.setDatas(payMerchantNumber);
        } catch (Exception e) {
            e.printStackTrace();
            returnBean.setReturnBean("105");
            return returnBean;
        }
        return returnBean;
    }


    @GetMapping(value = "rewarduserPay")
    @ApiOperation(value = "打赏支付接口")
    public ReturnBean rewarduserPay(@ApiParam(name = "paymerchantnumber", value = "订单号", required = true) @RequestParam String paymerchantnumber) {
        if (StringUtils.isEmpty(paymerchantnumber)) {
            return new ReturnBean("201", "paymerchantnumber不能为空");
        }
        ReturnBean returnBean = MfflConsultationService.ServicePay(paymerchantnumber, "/client/mfflConsultations/RewardPayCallback");

        if ("123".equals(returnBean.getErrCode())) {
            //订单号重复支付修改订单号，修改数据订单号
            //修改合同订单号  修改order订单号
            //订单操作
            MfflOrder Order = mfflOrderDao.getBypaymerchantnumber(paymerchantnumber);

            //重新生成订单号
            String newpayMerchantNumber = ProjectUtil.payMerchantNumber();

            //创建一个实体，防止在修改过程中其他信息改变的风险
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setId(Order.getId());
            mfflOrder.setPayMerchantNumber(newpayMerchantNumber);
            mfflOrder.setUpdtaeTime(new Date());
            mfflOrderDao.update(mfflOrder);
            ReturnBean returnbean = new ReturnBean();
            returnbean.setReturnBean("142");
            returnbean.setDatas(new HashMap<String, String>() {{
                put("newpayMerchantNumber", newpayMerchantNumber);
            }});
            return returnbean;
        }
        return returnBean;
    }


    /**
     * 打赏回调
     *
     * @return
     */
    @ApiIgnore
    @RequestMapping(value = "RewardPayCallback")
    public String RewardPayCallback(HttpServletRequest request) throws Exception {
        System.out.println("悬赏回调");
        //处理微信回调数据
        Map<String, String> returnmap = wxPayService.WechatPayCallback(request);

        //修改订单信息
        boolean b = MfflConsultationService.WechatPayCallback(returnmap);

        //微信回调数据
        return wxPayService.WechatPayCallbackReturnData(b);
    }

    @GetMapping("rewardpayorderquery")
    @ApiOperation(value = "打赏查询订单状态(不信任回调函数，)")
    public ReturnBean RewardPayorderquery(String payMerchantNumber) throws Exception {
        return MfflConsultationService.orderquery(payMerchantNumber);
    }
}